/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  DetectItemFragment.java   
 * @Package com.jiyi.activity.new_maintenance   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-8-30 下午2:45:48   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiyi.adapter.DetectItemAdapter;
import com.jiyi.bean.maintenance.DetectItemParent;
import com.jiyi.bean.maintenance.DetectSystemJson.Equipment;
import com.jiyi.bean.maintenance.DetectSystemJson.SecEquipment;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.CheckUploadEvent;
import com.jiyi.event.UpdateMainDetectEvent;
import com.jiyi.inteface.PickPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.PickPopView;
import com.jiyi.widget.picselect.PicFloderList_Activity;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.PermissionUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.DialogTool;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: DetectItemFragment
 * @Description:TODO(检测系统)
 * @author: HYM
 * @date: 2017-8-30 下午2:45:48
 * 
 */
public class DetectSystemFragment extends Fragment implements PickPopInterface {

	LayoutInflater inflater;

	@BindView(R.id.mainList)
	ExpandableListView mainList;
	@BindView(R.id.tvUpload)
	TextView tvUpload;
	@BindView(R.id.topDetectTip)
	TextView topDetectTip;

	DetectItemAdapter mDetectItemAdapter;

	ArrayList<DetectItemParent> mDetectItemParents = new ArrayList<DetectItemParent>();
	ViewGroup container;

	public PickPopView mPickPopView;
	// 图片路径
	private Uri mCameraUri;
	// 拍摄事件
	public final int CAMARE_CODE = 1;
	// 从相册选择事件
	public final int CHOOSE_PICTURE = 2;
	// 图片路径
	private String filePath;
	SecEquipment secEquipment;
	// 第几个父节点,父节点的position,页卡的类别,抽检项的item position
	int position,parentPosition,type,childPosition;
	String company_id;
	
	Dialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_detectitem, null, false);
		ButterKnife.bind(this, view);
		this.inflater = inflater;
		this.container = container;
		init();
		return view;
	}
	
	@Override
	public void onDestroyView() {
		DialogTool.hideDialog(dialog);
		super.onDestroyView();
	}

	private void init() {
		mPickPopView = new PickPopView(getContext(), this);
		getIntentData();
		setAdapter();
		getDetectItemData();
		checkUpload();
		EventBus.getDefault().register(this);
	}

	@Subscribe
	public void onCheckUploadEvent(CheckUploadEvent checkUploadEvent) {
		int catePosition = checkUploadEvent.position;
		if (this.position == catePosition) {
			checkUpload();
		}
	}

	@Override
	public void onDestroy() {
		DialogTool.hideDialog(dialog);
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-31
	 */
	private void getIntentData() {
		company_id = getArguments().getString(AppConfig.COMPANY_ID_KEY);
		parentPosition = getArguments().getInt("parentPosition");
		position = getArguments().getInt("position");
		childPosition = getArguments().getInt("childPosition");
		type = getArguments().getInt("type");
		String secEquipment = getArguments().getString("secEquipment");
		this.secEquipment = new Gson().fromJson(secEquipment,
				SecEquipment.class);
	}

	/**
	 * @author: HYM
	 * @Title: getDetectItemData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-8-30
	 */
	private void getDetectItemData() {
		for (int i = 0; i < secEquipment.getEquipment_list().size(); i++) {
			Equipment equipment = secEquipment.getEquipment_list().get(i);
			DetectItemParent parent = new DetectItemParent();
			parent.setTitle(equipment.getName());
			List<Equipment> childList = new ArrayList<Equipment>();
			Equipment child = equipment;
			childList.add(child);
			parent.setChildList(childList);
			mDetectItemParents.add(parent);
		}
		mDetectItemAdapter.notifyDataSetChanged();
		if (secEquipment.getIs_spotcheck() == 0) {
			topDetectTip.setVisibility(View.GONE);
		}
		else {
			topDetectTip.setVisibility(View.VISIBLE);
		}
	}

	private void setAdapter() {
		mDetectItemAdapter = new DetectItemAdapter(getContext(), position,
				mDetectItemParents, mPickPopView);
		mainList.setGroupIndicator(null);// 这个是去掉父级的箭头
		mainList.setAdapter(mDetectItemAdapter);
		mainList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				return true;
			}
		});

	}

	@Override
	public void OnShootListener() {
		if (PermissionUtil.checkPermission(this,PermissionUtil.CARAME))
		{
			useCamere();
		}

	}

	@Override
	public void OnAlbumListener() {
		// 添加图片 从相册
		PicSelectConstans.headUrl = "";
		Intent intent = new Intent(getContext(), PicFloderList_Activity.class);
		intent.putExtra("max", 4);
		startActivityForResult(intent, CHOOSE_PICTURE);
		mPickPopView.hidePopWindow();
	}

	/**
	 * <p>
	 * Title: OnCancleListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnCancleListener()
	 */
	@Override
	public void OnCancleListener() {

	}

	/**
	 * <p>
	 * Title: OnShowListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnHideListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see PickPopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMARE_CODE && resultCode == Activity.RESULT_OK) {
			if (!TextUtils.isEmpty(filePath)) {
				// 回调执行
				Log.e("", "回调执行拍摄");
				mDetectItemAdapter.getmList()
						.get(AppConfig.detectParentPosition).getChildList()
						.get(AppConfig.detectChildPosition).getImageList()
						.add(filePath);
				mDetectItemAdapter.notifyDataSetChanged();
				AppConfig.detectParentPosition = -1;
				AppConfig.detectChildPosition = -1;
				checkUpload();
			}
		} else if (requestCode == CHOOSE_PICTURE) {
			// 回调执行
			Log.e("", "回调执行相册");
			if (PicSelectConstans.publish_pics.size() > 0) {
				mDetectItemAdapter.getmList()
						.get(AppConfig.detectParentPosition).getChildList()
						.get(AppConfig.detectChildPosition).getImageList()
						.addAll(PicSelectConstans.publish_pics);
			}
			mDetectItemAdapter.notifyDataSetChanged();
			AppConfig.detectParentPosition = -1;
			AppConfig.detectChildPosition = -1;
			checkUpload();
		}
	}

	@OnClick({ R.id.tvUpload })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvUpload:
			doPost();
			break;
		default:
			break;
		}
	}

	boolean isAllDo() {
		boolean isAllDo = true;
		for (int i = 0; i < mDetectItemParents.size(); i++) {
			List<Equipment> equipments = mDetectItemParents.get(i)
					.getChildList();
			for (int j = 0; j < equipments.size(); j++) {
				if (equipments.get(j).getWithout() == 1 || equipments.get(j).getCannot_test() == 1) {
					isAllDo = true;
					break;
				}
				
				
				if (equipments.get(j).getImageList() == null
						|| equipments.get(j).getImageList().size() <= 0) {
					isAllDo = false;
					break;
				}
			}
			if (!isAllDo) {
				break;
			}
		}
		return isAllDo;
	}

	void checkUpload() {
		if (isAllDo()) {
			tvUpload.setEnabled(true);
		} else {
			tvUpload.setEnabled(false);
		}
	}

	void doPost() {
		String webApi = WebApi.MAINTENANCE_UPLOAD_DETECT_RECORD;

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put(AppConfig.COMPANY_ID_KEY, company_id);
		params.put(AppConfig.USER_ID, UserInfoUtil.getCurrentUserId() + "");
		params.put("user_name",
				ApplicationBase.LocalData.getString("user_name", ""));
		params.put("branch_id", UserInfoUtil.getCurrentUserDepartId() + "");

		PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
		postForm.params(params);
		List<Equipment> uploadData = new ArrayList<Equipment>();

		for (int i = 0; i < mDetectItemAdapter.getmList().size(); i++) {
			DetectItemParent detectItemParent = mDetectItemAdapter.getmList()
					.get(i);
			for (int j = 0; j < detectItemParent.getChildList().size(); j++) {
				Equipment detectItem = detectItemParent.getChildList().get(j);
				// 保存图片
				File file;
				for (int k = 0; k < detectItem.getImageList().size(); k++) {
					if (detectItem.getImageList().get(k).contains("http")) {
						continue;
					}
					file = new File(detectItem.getImageList().get(k));
					postForm.addFile(detectItem.getId() + "_image_" + (k+1), "pic" + (k + 1) + ".jpg", file);
				}
				detectItem.setState("1");
				uploadData.add(detectItem);
			}
		}
		Log.e("task_datas   ", new Gson().toJson(uploadData));
		params.put("task_datas", new Gson().toJson(uploadData));

		dialog = DialogTool.showDialog(dialog, getContext());
		
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				DialogTool.hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						//这个值判断是否已经全部完成了
//						JSONObject dataJson = new JSONObject(obj.getString("data"));
//						int fault_num = dataJson.getInt("fault_num");
//						int task_status = dataJson.getInt("task_status");
						// 异常数
						int faultNum = 0; 
						for (int i = 0; i < mDetectItemParents.size(); i++) {
							DetectItemParent detectItemParent = mDetectItemParents.get(i);
							for (int j = 0; j < detectItemParent.getChildList().size(); j++) {
								Equipment equipment = detectItemParent.getChildList().get(j);
								if(!TextUtils.isEmpty(equipment.getFault()) && equipment.getFault().equals("1"))
								{
									faultNum+=1;
								}
							}
						}
						Log.e("准备回传给主页  ", "当前position"+position +"  当前faultNum "+faultNum);
//						EventBus.getDefault().post(new MaintenanceTaskListEvent(type, parentPosition, childPosition, task_status,fault_num, 3));
						EventBus.getDefault().post(new UpdateMainDetectEvent(position,faultNum));
						mDetectItemAdapter.notifyDataSetChanged();
						
					} else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg(
								"尚未登录或该用户在其他地方登录，请重新登录！");
						// 清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context,
								true);
						return;
					} else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					DialogTool.hideDialog(dialog);
				}
			}
		});
	}


	private void useCamere()
	{
		File fileDir = new File(AppConfig.DIR_IMAGE);
		if (!fileDir.exists())
		{
			fileDir.mkdirs();
		}

		filePath = AppConfig.DIR_IMAGE+"temp"+new Date().getTime()+".jpg";
		File file = new File(filePath);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
		{
			mCameraUri = FileProvider.getUriForFile(getContext(),"com.swift.maintenance.updateprovider",file);
		}
		else
		{
			mCameraUri = CameraUtils.getOutputMediaFileUri(CameraUtils.MEDIA_TYPE_IMAGE);
			filePath=mCameraUri.getPath();
		}
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri);
		startActivityForResult(intent, CAMARE_CODE);
		mPickPopView.hidePopWindow();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == PermissionUtil.CARAME)
		{
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)
			{
				useCamere();
			}
			else
			{
				ToastUtil.getInstances().showMsg("无法访问相机");
			}
		}
	}
}
